package com.arenacloud.broadcast.example;

import android.graphics.Bitmap;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.arenacloud.broadcast.android.streaming.AspectFrameLayout;
import com.arenacloud.broadcast.android.BroadcastView;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


public class BroadcastTestActivity extends ActionBarActivity implements BroadcastView.BroadcastStatusCallback, BroadcastView.ScreenShotCallback{

    private final static String TAG = "AcSdk_BTestAct";
    private AspectFrameLayout mFrameLayout;
    private BroadcastView mBroadcastView;

    private ZoomControls zoomControls;
    private int zoomValue = 0;
    private final static int ZOOM_STEP = 20;
    //=======suker-2016-0518 add camera zoom focus =========================================>>end

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        Bundle extras = getIntent().getExtras();

        setContentView(R.layout.activity_arena_cloud_broadcast_test);
        mFrameLayout = (AspectFrameLayout) findViewById(R.id.cameraPreview_afl);
        mBroadcastView = (BroadcastView)findViewById(R.id.cameraPreview_surfaceView);
        // mBroadcastView.initBroadcast(extras, this);
        String pubKey = "fef19718136b161290d8d116b9912810"; // "86544f1e54d0b15dbb8bade300d1fe5f"
        mBroadcastView.initBroadcast(extras, pubKey, this);

        if (mBroadcastView.getAspectRatio() != 0) {
            mFrameLayout.setAspectRatio(mBroadcastView.getAspectRatio());
        }

        mBroadcastView.setBroadcastStatusCallback(this);
        mBroadcastView.setScreenShotCallback(this);
        mBroadcastView.setBitrate(800000); // suker-2016-0704 bitrate 800k

        //=======suker-2016-0518 add camera zoom focus =====================================>>begin
        zoomControls = (ZoomControls) findViewById(R.id.zoomControlId);
        if (null ==zoomControls)
        {
            Log.w(TAG, "zoom-control-null");
            return;
        }

        zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.w(TAG, "zoom-control-onclick-in, view:"+mBroadcastView);
                if ((null == zoomControls) || (null == mBroadcastView)) {
                    return;
                }
                boolean isEnable = true;
                zoomControls.setIsZoomOutEnabled(true);
                if (zoomValue > ZOOM_STEP) {
                    zoomValue -= ZOOM_STEP;
                } else {
                    zoomValue = BroadcastView.CAMERA_ZOOM_MIN;
                }
                if (BroadcastView.CAMERA_ZOOM_MIN == zoomValue) {
                    isEnable = false;
                }
                zoomControls.setIsZoomInEnabled(isEnable);
                mBroadcastView.onFocusZoom(zoomValue);
            }
        });

        zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.w(TAG, "zoom-control-onclick-out, view:"+mBroadcastView);
                if ((null == zoomControls) || (null == mBroadcastView)) {
                    return;
                }
                boolean isEnable = true;
                zoomControls.setIsZoomInEnabled(true);
                if (zoomValue < BroadcastView.CAMERA_ZOOM_MAX) {
                    zoomValue += ZOOM_STEP;
                } else {
                    zoomValue = BroadcastView.CAMERA_ZOOM_MAX;
                }
                if (BroadcastView.CAMERA_ZOOM_MAX == zoomValue) {
                    isEnable = false;
                }
                zoomControls.setIsZoomOutEnabled(isEnable);
                mBroadcastView.onFocusZoom(zoomValue);
            }
        });
    }


    public boolean onTouchEvent(MotionEvent event) {
        Log.w(TAG, "on-touch-run | onTouchEvent --> " + getTouchAction(event.getAction()));
        if (null == mBroadcastView) {
            return false;
        }
        mBroadcastView.onTouchFocus(event);
        Log.w(TAG, "on-touch-ext");
        return super.onTouchEvent(event);
    }

    public static String getTouchAction(int actionId) {
        String actionName = "Unknow:id=" + actionId;
        switch (actionId) {
            case MotionEvent.ACTION_DOWN:
                actionName = "ACTION_DOWN";
                break;
            case MotionEvent.ACTION_MOVE:
                actionName = "ACTION_MOVE";
                break;
            case MotionEvent.ACTION_UP:
                actionName = "ACTION_UP";
                break;
            case MotionEvent.ACTION_CANCEL:
                actionName = "ACTION_CANCEL";
                break;
            case MotionEvent.ACTION_OUTSIDE:
                actionName = "ACTION_OUTSIDE";
                break;
        }
        return actionName;
    }

    public void onClick(View v) {
        if (null == mBroadcastView) {
            return;
        }
        int i = v.getId();
        if (i == R.id.toggleRecording_button) {
            new  Thread(new Runnable() {
                @Override
                public void run() {
                    if (mBroadcastView.isRecordingEnabled()) {
                        mBroadcastView.toggleRecording();
                    } else {
//                         String pubUrl = "rtmp://172.16.208.102/myapp/suker";
//                         String pubUrl = "rtmp://172.16.208.103/myapp/suker";
//                         String pubUrl = "rtmp://test-ws-pub.arenacdn.com/prod/upMRrQzytzhtEAC2?pass=c0d677116062fed9d0a66cf84678a73c";
                // player=rtmp://test-ws-live.arenacdn.com/prod/upMRrQzytzhtEAC2?pass=c0d677116062fed9d0a66cf84678a73c
//                        String pubUrl = "rtmp://172.16.22.182/myapp/live";
//                       String pubUrl = "rtmp://172.16.22.173/myapp/live";
                        String pubUrl = "rtmp://test-kw-pub.arenacdn.com/prod/yIynaa0M8swFEApb?pass=1c72136f29a7afa4579fd9dd16f7762f";
                        String pukRoom = "10241";

                        String path = pubUrl;
                        //  String pubKey = "fef19718136b161290d8d116b9912810";
                        String prjId =  "f88624ad0cf2380b22100336";
                        String deviceId = "123456789";
                        String roomId = "12305";
                        String roomName = "jingcaijinqiu";
                        String channelId = "360market";
                        boolean isRegister = false;
                        String reserved = "reserved";

                        mBroadcastView.setPublishPara(path, prjId, deviceId, roomId, roomName, channelId, isRegister, reserved);
                        // mBroadcastView.setPublishUrl(pubUrl, pukRoom);
                        mBroadcastView.toggleRecording();
                    }
                }
            }).start();

        } else if (i == R.id.toggleSwitch_button) {
            mBroadcastView.switchCamera();
        } else if (i == R.id.toggleScreenShot_button) {
            mBroadcastView.takeScreenShot();
        } else if (i == R.id.restart_button) {
            new  Thread(new Runnable() {
                @Override
                public void run() {
                    mBroadcastView.apiRestartPush();
                }
            }).start();
        }
        else {
        }
    }

    @Override
    protected void onResume() {
        Log.w(TAG, "Act-on-Resume-run");
		mBroadcastView.onResumeHandler();
        super.onResume();
        Log.w(TAG, "Act-on-Resume-ext");
    }

    @Override
    protected void onPause() {
        Log.w(TAG, "Act-on-Pause-run");
        super.onPause();
        mBroadcastView.onPauseHandler();
        Log.w(TAG, "Act-on-Pause-ext");
    }

    @Override
    protected void onDestroy() {
        Log.w(TAG, "Act-on-Destroy-run");
        mBroadcastView.onDestroyHandler();
        super.onDestroy();
        Log.w(TAG, "Act-on-Destroy-ext");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_arena_cloud_broadcast, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void broadcastStatusUpdate(final BroadcastView.BROADCAST_STATE state) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView statusTextView = (TextView) findViewById(R.id.streamingStatus);

                String statusText;
                switch (state) {
                    case PREPARING:
                        statusText = "Preparing";
                        break;
                    case CONNECTING:
                        statusText = "Connecting";
                        break;
                    case READY:
                        statusText = "Ready";
                        break;
                    case STREAMING:
                        statusText = "Streaming";
                        break;
                    case SHUTDOWN:
                        statusText = "Shutdown";
                        break;
                    case DISCONNECT:
                        statusText = "Disconnect";
                        break;
                    default:
                        statusText = "Unknown";
                        break;
                }
                statusTextView.setText(statusText);
            }
        });
    }

    private Bitmap bitmap;

    @Override
    public void onScreenShotEvent(final Bitmap bitmap) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                File file = new File("/sdcard" + "/ArenaCloud/ScreenShot/");
                if (!file.exists()) {
                    file.mkdir();
                }

                String savePath = "/sdcard" + "/ArenaCloud/ScreenShot/" + System.currentTimeMillis() + ".jpeg";
                try {
                    FileOutputStream fout = new FileOutputStream(savePath);
                    BufferedOutputStream bos = new BufferedOutputStream(fout);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                    bos.flush();
                    bos.close();

                    bitmap.recycle();

                    Toast.makeText(BroadcastTestActivity.this, "YOU HAVE SAVED A SCREENSHOT",
                    Toast.LENGTH_LONG).show();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
